package com.msb.mall.controller;

import com.alibaba.fastjson.JSON;
import com.msb.common.constant.AuthConstant;
import com.msb.common.constant.SMSConstant;
import com.msb.common.exception.BizCodeEnume;
import com.msb.common.utils.R;
import com.msb.common.vo.MemberVO;
import com.msb.mall.feign.MemberFeignService;
import com.msb.mall.feign.ThirdPartFeignService;
import com.msb.mall.vo.LoginVo;
import com.msb.mall.vo.UserRegisterVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author zhangjiajun
 * @Email zhangjiajun@hydsoft.com
 * @Description
 * @Date 2025/7/30 21:55
 */
@Controller
public class LoginController {

    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;


    /**
     * 登录的方法
     * @return
     */
    @PostMapping("/login")
    public String login(LoginVo loginVo , RedirectAttributes redirectAttributes, HttpSession session) {
        R r = memberFeignService.login(loginVo);
        if(r.getCode() == 0){
            // 表示登录成功

            String entityJson = (String) r.get("entity");
            MemberVO memberVO = JSON.parseObject(entityJson, MemberVO.class);
            memberVO.setNickname(StringUtils.isNotBlank(memberVO.getNickname())?memberVO.getNickname():memberVO.getUsername());

            session.setAttribute(AuthConstant.AUTH_SESSION_REDIS, memberVO);

            return "redirect:http://mall.msb.com/home";
        }
        redirectAttributes.addAttribute("errors",r.get("msg"));
        // 表示登录失败,重新跳转到登录页面
        return "redirect:http://auth.msb.com/login.html";
    }


    /**
     * 注册
     * @param vo
     * @param result
     * @param model
     * @return
     */
    @PostMapping("/sms/register")
    public String register(@Valid UserRegisterVO vo, BindingResult result, Model model) {
            HashMap<String, String> map = new HashMap<>();
        if (result.hasErrors()) {
            //提交的数据不合法
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                String field = fieldError.getField();
                String defaultMessage = fieldError.getDefaultMessage();
                map.put(field, defaultMessage);
            }
            model.addAttribute("error", map);
            return "/reg";
        } else {
            String code = redisTemplate.opsForValue().get(SMSConstant.SMS_CODE_PREFIX + vo.getPhone());
            if (!vo.getCode().equals(code.split("_")[0])) {
                map.put("code", "验证码错误");
                return "reg";
            } else {
                //验证码正确
                //删除验证码
                redisTemplate.delete(SMSConstant.SMS_CODE_PREFIX + vo.getPhone());

                //远程调用服务完成注册功能
                System.out.println("验证码正确");
                R r = memberFeignService.register(vo);
                if (r.getCode() == 0) {
                    return "redirect:http://auth.msb.com/login.html";
                } else {
                    // 注册失败
                    map.put("msg",r.getCode()+":"+r.getMsg());
                    model.addAttribute("error",map);
                    return "/reg";
                }

            }

        }
    }


    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendSmsCode(@RequestParam("phone") String phone) {
        //防止60内重复发送
        String value = redisTemplate.opsForValue().get(SMSConstant.SMS_CODE_PREFIX + phone);
        if (value != null && StringUtils.isNotBlank(value)) {
            Long preTime = Long.parseLong(value.split("_")[1]);
            if(System.currentTimeMillis() - preTime < 120000) {
                //说明验证码发送不足2min
                return R.error(BizCodeEnume.VALUE_SMS_EXCEPTION.getCode(), BizCodeEnume.VALUE_SMS_EXCEPTION.getMsg());
            }

        }
        //生成验证码
        String code = generateSixDigitCode();
//        thirdPartFeignService.sendSmsCode(phone, code);
        //放到redis   key: sms:code:手机号  123456
        code +=  "_" + System.currentTimeMillis();
        redisTemplate.opsForValue().set(SMSConstant.SMS_CODE_PREFIX + phone, code, 5, TimeUnit.MINUTES);
        System.out.println("code=" + code);
        return R.ok();
    }


    public static String generateSixDigitCode() {
        int code = (int)((Math.random() * 9 + 1) * 100000); // 保证第一位不是0
        return String.valueOf(code);
    }
}
